import React, { useEffect, useState } from 'react'
import Taro,{useDidShow, useReachBottom} from '@tarojs/taro'
import {View,Image,Text,Swiper,SwiperItem} from '@tarojs/components'
import './index.scss'

let filters = {
  page:1,
  pageSize:10
}
export default function HomeMovie() {
  let buttonStatus = {
    pre_sale:'预售',
    favorites:'想看',
    already_favorites:'已想看',
    sale:'购票'
  }
  let capsule = {}
  if(process.env.TARO_ENV === 'weapp') capsule = Taro.getMenuButtonBoundingClientRect()
  const tabsList = ['正在热映','即将上映']
  const [curTabs,setCurTabs] = useState(0)
  const [cinemaInfo,setCinemaInfo] = useState({})
  const [list,setList] = useState([])
  const [banner,setBanner] = useState([])
  useEffect(()=>{
    Taro.$get('/news/news/advertisingPosition/selectAdvertisingListByAlias/cinema_top').then(res=>{
      if(res.code == '1') setBanner(res.content?.advertisesList)
    })
    const tabs = Taro.getCurrentInstance()?.router.params.tabs || 0
    setCurTabs(tabs)
    setCinemaInfo(Taro.getStorageSync('selectMerchant'))
    Taro.eventCenter.on('updateMerchant',e=>{
      setCinemaInfo(Taro.getStorageSync('selectMerchant'))
      _getData({page:1},e=>{
        setList(e)
      })
    })
  },[])
  useDidShow(()=>{
    if(Taro.getStorageSync('position') && !Taro.getStorageSync('selectMerchant')?.id){
      Taro.navigateTo({
        url:'/mainPages/select-cinema/index'
      })
    }
  })
  useEffect(()=>{
    if(curTabs >= 0){
      setList([]);
      Taro.showLoading({title:'加载中...'})
      _getData({page:1},e=>{
        setList(e)
      })
    }
  },[curTabs])
  const handleChangeTabs =e=>{ //  切换tabs
    setCurTabs(e);
  }
  useReachBottom(()=>{
    if(filters.totalCount > list.length){
      // _getData({page:filters.page+1},data=>{
      //   setList([...list,...data?.list])
      // })
    }
  })
  const handleBannerJump =url=>{
    if(url?.includes('openmini')){
      let appId = ''
      if(process.env.TARO_ENV === 'weapp') appId = getParames(url).wxAppId
      Taro.navigateToMiniProgram({
        appId
      })
      return;
    }
    if(url?.includes('https://')){
      url = `/pages/fineEngine/webView?url=${encodeURIComponent(url)}`
    }
    Taro.navigateTo({
      url
    })
  }
  
  const handleButton = res=>{  ///  点击购票,预售,想要按钮
    if(res.buttonStatus == 'sale'){
      Taro.verifyLogin()
      Taro.navigateTo({
        url:`/mainPages/plan/index?id=${res.id}`
      })
    }
    if(res.buttonStatus == 'pre_sale'){
      Taro.verifyLogin()
    }
    if(res.buttonStatus == 'favorites' || res.buttonStatus == 'already_favorites'){
      if(res.isLike){
        Taro.$del('/social/topicLike/v1',{appId:Taro.$mpAppid,topicId:res.id}).then(ret=>{
          if(ret.code == '1'){
            res.isLike = false
            setList((pre)=>{
              return pre.slice()
            })
          }
        })
        return;
      }
      Taro.$post('/social/topicLike',{appId:Taro.$mpAppid,topicId:res.id}).then(ret=>{
        if(ret.code == '1'){
          res.isLike = true
          setList((pre)=>{
            return pre.slice()
          })
        }
      })
    }
  }

  const _getData = (e,fun)=>{
    const data = {
      // page: filters.page,
      // pageSize: filters.pageSize,
      cinemaId:Taro.getStorageSync('merchantId'),
      ...e
    }
    Taro.$get(`${curTabs==0?'/cinema-app/api/v1/film/hotFilm':'/cinema-app/api/v1/film/comingSoon'}`,data,'1').then(res=>{
      if(res.code == '1'){
        fun(res.content)
        if(curTabs == 1){
          let topicIds = [],arr = res.content || []
          arr?.map(res=>{
            res.filmList?.map(ret=>{
              if(ret.buttonStatus == 'favorites') topicIds.push(ret.id)
            })
          })
          Taro.$post('/social/topicLike/isLikeByTopicIds',{appId:Taro.$mpAppid,topicIds}).then(res=>{
            if(res.code == '1' && res.content?.length){
              res.content?.map(ret=>{
                arr?.map(result=>{
                  if(result.id == ret.topicId){
                    result.isLike = ret.isLike
                  }
                })
              })
              setList((pre)=>{
                return arr.slice()
              })
            }
          })
        }
        // filters = {...filters,...res.content}
      }
    })
  }
  return (
    <View className='home-movie'>
      <View className="home-nav-bar" style={{paddingTop:capsule.top+'PX'}}>
        <View className="box-flex" style={{minHeight: capsule.height+'px'}} onClick={()=>{
          Taro.navigateTo({
            url:'/mainPages/select-cinema/index'
          })
        }}>
          {cinemaInfo.cinemaNickName || "请选择影院"}
          <Text className='at-icon at-icon-chevron-down' style={{marginLeft:4}}></Text>
          {cinemaInfo.distance?<View className="distance">距离您 {cinemaInfo.distance}</View>:null}
        </View>
      </View>
      {banner?.length?
        <Swiper className='movie-banner' autoplay>
          {banner.map(res=>{
            return <SwiperItem key={res.id} onClick={()=>{handleBannerJump(res.url)}}>
              <Image lazyLoad src={res.imageUrl} className='banner-img' mode='aspectFill' />
            </SwiperItem>
          })}
        </Swiper>
      :null}
      <View className="movie-tabs">
        {tabsList?.map((res,idx)=>{
          return <View key={res} className={`tabs-item ${idx == curTabs?'active':''}`} onClick={()=>{handleChangeTabs(idx)}}>{res} {idx==0?<Image src={require('@/images/hoting.svg')} mode="widthFix" style={{width:'16px'}} />:null}</View>
        })}
      </View>
      {curTabs == 0?list.length?<View className='hoting-list'>
        {list?.map((res,idx)=>{
          return <View className="list-item" key={idx}>
            <View className="item-img" onClick={()=>{
              Taro.navigateTo({
                url:`/mainPages/video-detail/index?id=${res.id}`
              })
            }}>
              <Image className='img' lazyLoad src={!res.filmPosterUrl?.includes('alicdn')?res.filmPosterUrl:res.filmPosterUrl+'_240x240'} mode='aspectFill' />
            </View>
            <View className="item-info" onClick={()=>{
              Taro.navigateTo({
                url:`/mainPages/video-detail/index?id=${res.id}`
              })
            }}>
              <View className="info-h2">
                <View className='dot'>{res.filmNickName}</View>
                {res.filmVersion?
                <View className="info-tags">
                  {res.filmVersion?.map(res=>{
                    return <Text className='tags-span' key={res}>{res}</Text>
                  })}
                </View>:null}
              </View>
              <View className="box-flex" style={{alignItems:'center'}}>
                <View style={{flex:1}}>
                  <View className="info-p dot">评分 {res.score || 0}
                  {/* <Text style={{fontSize:'9px',color:'#D2D3D4'}}>|</Text> 1.7万人评 */}
                  </View>
                  {res.directors?.length?<View className="info-p dot">导演: {res.directors?.map(ret=>{
                    return <Text style={{marginRight:4}}>{ret}</Text>
                  })}</View>:null}
                  {res.actors?.length?<View className="info-p dot">主演: {res.actors?.map(ret=>{
                    return <Text style={{marginRight:4}}>{ret}</Text>
                  })}</View>:null}
                </View>
                <View className={`item-button ${res.buttonStatus}`} onClick={()=>{
                  handleButton(res)
                }}>{buttonStatus[res.buttonStatus]}</View>
              </View>
            </View>
          </View>
        })}
      </View>:
      <View className='var-empty'>
        <Image src={require('@/images/common/no-movie.png')} className='img' />
        <View className="h2">暂无影片场次</View>
        <View className="p">No movie showings available</View>
      </View>:
      <View className='upcoming-list'>
        {list?.length?list.map((res)=>{
          return <>
          <View className="list-title" key={res.date}>
            <Text>{res.cnWeek}</Text>
            {res.date}
          </View>
          {res.filmList?.map((ret,idx)=>{
            return <View className="list-item" key={idx}>
              <View className="item-img" onClick={()=>{
                Taro.navigateTo({
                  url:`/mainPages/video-detail/index?id=${ret.id}`
                })
              }}>
                <Image lazyLoad src={!ret.filmPosterUrl?.includes('alicdn')?ret.filmPosterUrl:ret.filmPosterUrl+'_240x240'} className='img' mode='aspectFill' />
              </View>
              <View className="item-info" onClick={()=>{
                Taro.navigateTo({
                  url:`/mainPages/video-detail/index?id=${ret.id}`
                })
              }}>
                <View className="info-h2">
                  <View className='dot'>{ret.filmNickName}</View>
                  {ret.filmVersion?
                  <View className="info-tags">
                    {ret.filmVersion?.map(res=>{
                      return <Text className='tags-span' key={res}>{res}</Text>
                    })}
                  </View>:null}
                </View>
                <View className="box-flex" style={{alignItems:'center'}}>
                  <View style={{flex:1}}>
                    <View className="info-p dot">{ret.publishDate}上映</View>
                    {ret.directors?.length?<View className="info-p dot">导演: {ret.directors?.map(ret=>{
                      return <Text style={{marginRight:4}}>{ret}</Text>
                    })}</View>:null}
                    {ret.actors?.length?<View className="info-p dot">主演: {ret.actors?.map(ret=>{
                      return <Text style={{marginRight:4}}>{ret}</Text>
                    })}</View>:null}
                  </View>
                  <View className={`item-button ${ret.buttonStatus == 'favorites'?ret.isLike?'already_favorites':'favorites':ret.buttonStatus}`} onClick={()=>{
                    handleButton(ret)
                  }}>{ret.buttonStatus=='favorites'?ret.isLike?'已想看':'想看':buttonStatus[ret.buttonStatus]}</View>
                </View>
              </View>
            </View>
          })}
          </>
        }):<View className='var-empty'>
          <Image src={require('@/images/common/no-movie.png')} className='img' />
          <View className="h2">暂无影片场次</View>
          <View className="p">No movie showings available</View>
        </View>}
      </View>}
    </View>
  )
}
